package net.csdra.libraryborrowing.service.book;

import net.csdra.libraryborrowing.domain.book.BookInfo;
import net.csdra.libraryborrowing.domain.book.BookInfoRepository;
import net.csdra.libraryborrowing.service.user.CurrentUserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.nio.file.AccessDeniedException;
import java.util.List;

/**
 * Created by xiaomi on 2017/10/16.
 */
@Service
public class BookInfoServiceImpl implements BookInfoService {

    @Autowired
    CurrentUserInfo currentUserInfo;
    @Autowired
    BookInfoRepository bookInfoRepository;

    @Override
    public Page<BookInfo> searchBookInfo(SearchBookInfo searchBookInfo) {
        Assert.state(searchBookInfo != null && StringUtils.hasText(searchBookInfo.getKey()), "@请输入关键字！");
        Page<BookInfo> bookInfoPage = bookInfoRepository.searchBookByKey(
                searchBookInfo.getKey(),
                new PageRequest(searchBookInfo.getPage(), searchBookInfo.getSize(), Sort.Direction.DESC, "lastModifiedTime")
        );
        return bookInfoPage;
    }

    @Override
    public List<BookInfo> getBookInfoByBookStorageBox(GetBookInfoByBookStorageBox getBookInfoByUserBorrow) throws AccessDeniedException {
        List<BookInfo> bookInfoList = bookInfoRepository.getBookInfoByBookStorageBox(currentUserInfo.get().getId());
        return bookInfoList;
    }

    @Override
    public BookInfo getBookDetail(GetBookDetail getBookDetail) {
        BookInfo bookInfo = bookInfoRepository.findOne(getBookDetail.bookInfoId);
        return bookInfo;
    }

    @Override
    public Page<BookInfo> getBookInfoByUserBorrow(GetBookInfoByUserBorrow getBookInfoByUserBorrow) throws AccessDeniedException {
        Page<BookInfo> bookInfoPage = bookInfoRepository.getBookInfoByUserBorrow(
                currentUserInfo.get().getId(),
                getBookInfoByUserBorrow.userBorrowState,
                new PageRequest(getBookInfoByUserBorrow.getPage(), getBookInfoByUserBorrow.getSize(), Sort.Direction.ASC, "lastModifiedTime")
        );
        return bookInfoPage;
    }

    @Override
    public Page<BookInfo> getBookListByCategory(GetBookListByCategory getBookListByCategory) {
        Page<BookInfo> bookInfoPage = bookInfoRepository.getBookListByCategory(
                getBookListByCategory.getCategoryIds(),
                new PageRequest(getBookListByCategory.getPage(), getBookListByCategory.getSize(), Sort.Direction.ASC, "lastModifiedTime")
        );
        return bookInfoPage;
    }
}
